package com.qianli.cashmama.trade.common.utils.signature;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Base64编码解码工具类
 *
 * @author liuming
 * Created on 下午11:40 2018/8/12.
 */
public class Base64ConvertUtil {

    /**
     * 字符串Base64加密
     *
     * @param string
     * @return
     */
    public static String stringToBase64(String string) {
        byte[] bytes = string.getBytes();
        Base64 base64 = new Base64();
        bytes = base64.encode(bytes);
        return new String(bytes);
    }

    /**
     * PDF转Base64字符串
     *
     * @param contractFileBytes
     * @return
     * @throws IOException
     */
    public static String pdfToBase64(byte[] contractFileBytes) throws IOException {
        Base64 base64 = new Base64();
        byte[] encode = base64.encode(contractFileBytes);
        return new String(encode);
    }

    /**
     * 将Base64加密过的字符串转成PDF
     *
     * @param base64Pdf
     * @param targetPath
     * @throws IOException
     */
    public static String base64ToPdf(String base64Pdf, String targetPath) throws IOException {
        Base64 base64 = new Base64();
        byte[] buffer = base64.decode(base64Pdf);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
        return targetPath;
    }


    public static InputStream base64ToPdf(String base64Pdf) {
        Base64 base64 = new Base64();
        byte[] buffer = base64.decode(base64Pdf);
        return new ByteArrayInputStream(buffer);
    }
}
